package com.example.eback.controller;

import com.example.eback.constans.UserRegistryCode;
import com.example.eback.entity.User;
import com.example.eback.result.Result;
import com.example.eback.result.ResultCode;
import com.example.eback.result.ResultFactory;
import com.example.eback.service.UserService;
import com.example.eback.util.SendMailUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Login and register controller.
 *
 * @author Evan
 * @date 2019/4
 */
@ApiOperation(value = "登录注册相关接口")
@RestController
@Slf4j
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    SendMailUtil sendMailUtil;
    @Value("${from_email}")
    String from_email;
    @Value("${from_email_pwd}")
    String from_email_pwd;
    @Value("${avatar}")
    String avatar;
    @ApiOperation(value = "登录", notes = "账号+密码")
    @PostMapping("/login")
    public Result login(@RequestBody @Valid User requestUser) {

        String username = requestUser.getUsername();
        username = HtmlUtils.htmlEscape(username);

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, requestUser.getPassword());
        usernamePasswordToken.setRememberMe(true);
        try {
            subject.login(usernamePasswordToken);
            log.info("{}登录成功", username);
            return ResultFactory.buildSuccessResult(username);
        } catch (IncorrectCredentialsException e) {
            log.warn("{}登录，密码错误", username);
            return ResultFactory.buildFailResult("密码错误");
        } catch (UnknownAccountException e) {
            return ResultFactory.buildFailResult("账号不存在");
        }

    }

//    @PostMapping("/api/register")
//    public Result register(@RequestBody User user) {
//        log.info("{}注册", user.getUsername());
//        UserRegistryCode status = userService.register(user);
//        return ResultFactory.buildFailResult(status.getMsg());
//    }
    @PostMapping("/register")
    public Result SaveRegister(@RequestBody Map<String, Object> json) throws Exception {
        String email = (String) json.get("email");
        String phone = (String) json.get("phone");
        String username = (String) json.get("username");
        String password = (String) json.get("password");
        String repassword = (String) json.get("repassword");
        String code = (String) json.get("code");
//        String avatar=
        ValueOperations<String,String> operations=redisTemplate.opsForValue();
        String get_code=operations.get(email);
//        int SureInformation=1;
        String message= sendMailUtil.CheckInformation(phone,username,password,email);
        if(!Objects.equals(message, "填写正确")){
//            SureInformation=0;
            if(Objects.equals(message, "您已注册")){
                return ResultFactory.buildFailResult("您已注册");
            }
            else{
            return ResultFactory.buildFailResult("填写错误");
            }
        }
        if(!sendMailUtil.CheckPassword(password,repassword) ||get_code==null|| !Objects.equals(code, get_code)){
//            SureInformation=0;
            return ResultFactory.buildFailResult("邮箱或密码或验证码不正确");
        }
        else{
            User user = new User();
            user.setUsername(username);
            user.setPhone(phone);
            user.setPassword(password);
            user.setEmail(email);
            UserRegistryCode status = userService.register(user);
            return ResultFactory.buildFailResult(status.getMsg());
        }
    }
    //发送验证码
    @RequestMapping("/sendCode")
    @ResponseBody
    public Result sendCode(@RequestBody Map<String,Object> json) {
        String message="";
        try {
            String name = (String) json.get("name");
            String email = (String) json.get("email");
            //判断邮箱格式是否正确
            if (sendMailUtil.isEmail(email)) {
                StringBuilder code = sendMailUtil.CreateCode();
                ValueOperations<String, String> operations = redisTemplate.opsForValue();
                if (operations.get(email) != null) {
                    return ResultFactory.buildResult(ResultCode.SUCCESS,"验证码已发送,请三分钟后重试",null);
                } else {
                    operations.set(email, String.valueOf(code));
                    redisTemplate.expire(email, 3, TimeUnit.MINUTES);
                    message = sendMailUtil.sendQQEmail(from_email, from_email_pwd, email, String.valueOf(code), name);
                    return ResultFactory.buildResult(ResultCode.SUCCESS,"验证码发送成功",null);
                }
            } else {
                return ResultFactory.buildFailResult("邮箱格式不正确");
            }
        } catch (Exception e) {
            log.info(String.valueOf(e));
            return ResultFactory.buildFailResult(UserRegistryCode.UNKNOWN.getMsg());//"出现未知错误"
        }
    }

    @GetMapping("/logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        System.out.println(SecurityUtils.getSubject().getPrincipal().toString());
        return ResultFactory.buildSuccessResult("成功登出");
    }
    @RequiresPermissions("admin")
    @GetMapping("/admin/authentication")
    public Result authentication() {
        return ResultFactory.buildSuccessResult("success");
    }

}
